package com.pifuke.patient;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import cn.o.app.event.listener.OnSelectedChangeListener;
import cn.o.app.json.JsonUtil;
import cn.o.app.media.PickContactTask;
import cn.o.app.media.PickContactTask.PickContactListener;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OActionSheet;
import cn.o.app.ui.OActionSheet.OnActionItemClickListener;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.o.app.ui.OFragmentFrame;
import cn.o.app.ui.OTab;

import com.evan.common.share.ShareCallBack;
import com.evan.common.share.ShareQQUtils;
import com.evan.common.share.ShareWXUtils;
import com.smiier.skin.CreateQuestionActivity;
import com.smiier.skin.DoctorProfileEditActivity;
import com.smiier.skin.LoginActivity;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.net.QuestionLimitCheckTask;
import com.smiier.skin.net.QuestionLimitCheckTask.QuestionLimitCheckRequest;
import com.smiier.skin.net.QuestionLimitCheckTask.QuestionLimitCheckResponse;
import com.smiier.skin.net.SysGetVerTask;
import com.smiier.skin.net.SysGetVerTask.SysGetVerRequest;
import com.smiier.skin.net.SysGetVerTask.SysGetVerResponse;
import com.smiier.skin.net.SysGetVerTask.SysVerItem;
import com.smiier.skin.net.SysGetVerTask.SysVerList;
import com.smiier.skin.net.SysShareCallBackTask;
import com.smiier.skin.net.SysShareCallBackTask.SysShareCallBackRequest;
import com.smiier.skin.net.entity.Hospital;
import com.smiier.skin.net.entity.Hospital.AreaHospital;
import com.smiier.skin.net.entity.Hospital.HospitalItem;
import com.smiier.skin.net.entity.Hospital.SubAreaHospital;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.ui.PersonalPatientFragment;
import com.smiier.skin.ui.QuestionFragment;
import com.smiier.skin.ui.QuestionFragment.ContactActionItem;
import com.smiier.skin.ui.QuestionLimitDialog;
import com.smiier.skin.ui.QuestionLimitDialog.QuestionLimitDialogListener;
import com.smiier.skin.ui.SessionFragment;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.utils.Util;

public class NavigateActivity extends BasicActivity {
	protected OFragmentFrame mFrame;
	protected OTab mTab;

	protected int mLastInterceptTabIndex = -1;

	protected boolean mSmsCatching = false;

	protected boolean mCheckingQuestionLimit = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_navigate);

		// Button button = (Button) findViewById(R.id.test);

		GlobalSettings.appStart = true;

		GlobalSettings.isDoctor = false;

		// 检查版本更新
		checkVersion(true, null);

		// AppCheckCacheUpdate.doCheckDataVersion();
		doCheckDataVersion();

		mFrame = findViewById(R.id.frame, OFragmentFrame.class);

		mTab = findViewById(R.id.tab, OTab.class);

		SessionFragment sessionFragment = findViewById(R.id.session_fragment,
				SessionFragment.class);

		sessionFragment.setBageViewTarget(mTab.getChildAt(1));

		PersonalPatientFragment patientFragment = findViewById(
				R.id.personal_fragment, PersonalPatientFragment.class);
		patientFragment.setBageViewTarget(mTab.getChildAt(4));

		if (GlobalSettings.sUser == null) {
			CommonUtility.userGet(getApplicationContext());
		}
		mTab.setSelectedIndex(0);
		mTab.setOnSelectedChangeListener(new OnSelectedChangeListener() {

			@Override
			public boolean onInterceptChange(View v, int index) {
				if (index == 0 || index == 3) {
					mLastInterceptTabIndex = -1;
					return false;
				}
				if (GlobalSettings.sUser == null
						|| GlobalSettings.sToken == null) {
					Intent i = new Intent(getContext(), LoginActivity.class);
					i.putExtra(Constant.USER_TYPE, 1);
					startActivity(i);
					mLastInterceptTabIndex = index;
					return true;
				}
				if (index == 2) {

					mLastInterceptTabIndex = -1;
					onClickAddQuestion();

					return true;
				}

				if (CommonUtility.isDoctor()) {
					if (index == 3) {
						if (GlobalSettings.sUser.Is_Cert != 1
								&& GlobalSettings.sUser.Is_Cert != 3) {
							Intent intent = new Intent(NavigateActivity.this,
									DoctorProfileEditActivity.class);
							intent.putExtra(Constant.IDENTITY_KEY, true);
							startActivity(intent);
							mLastInterceptTabIndex = index;
							return true;
						}
					}
				}
				mLastInterceptTabIndex = -1;
				return false;
			}

			@Override
			public void onChanged(View v, int index) {
				if (index > 2) {
					index--;
				}
				mFrame.setSelectedIndex(index);
			}
		});
		IntentFilter filter = new IntentFilter("send");
		registerReceiver(xxReceiver, filter);

		mFrame.setSelectedIndex(0);
		// 监听短信
		getContext().getContentResolver().registerContentObserver(
				Uri.parse("content://sms/"), true,
				new ContentObserver(new Handler()) {

					@Override
					public void onChange(boolean selfChange) {
						if (!mSmsCatching) {
							return;
						}
						Cursor cursor = getContext().getContentResolver()
								.query(Uri.parse("content://sms/outbox"), null,
										null, null, null);
						if (cursor.moveToFirst()) {
							String body = cursor.getString(cursor
									.getColumnIndex("body"));
							if (body.contains("皮肤科医生")) {
								mSmsCatching = false;
								doShareCallBack();
							}
						}
					}

				});

		Intent refreshIntent = new Intent(Constant.RECIVER_SESSION_TAB_NOREAD);
		getContext().sendBroadcast(refreshIntent);

	}

	protected void showQuestionLimitDialog() {
		QuestionLimitDialog dialog = new QuestionLimitDialog(getContext());
		dialog.setListener(new QuestionLimitDialogListener() {

			@Override
			public void onInviteWeixin() {
				String title = "皮肤科医生";
				String description = "还在为皮肤问题烦恼？大牌专家都在这里，去问问他们吧～";
				String url = "http://www.pifupro.com/download.html";
				ShareWXUtils.getInstance(getContext()).share2WXWEB(url, title,
						description, false);

			}

			@Override
			public void onInviteQQ() {
				String title = "皮肤科医生";
				String description = "还在为皮肤问题烦恼？大牌专家都在这里，去问问他们吧～";
				String url = "http://www.pifupro.com/download.html";
				ShareQQUtils.getInstance((Activity) getContext()).share(url,
						title, description);
				ShareQQUtils.getInstance((Activity) getContext())
						.setOnCompleteCallBack(new ShareCallBack() {

							@Override
							public void callback(Object obj) {
								doShareCallBack();
							}
						});

			}

			@Override
			public void onInviteContacts() {
				PickContactTask task = new PickContactTask(
						NavigateActivity.this,
						GlobalSettings.REQUEST_CODE_PICK_CONTACT);
				if (task.pickContact()) {
					task.setListener(new PickContactListener() {

						@Override
						public void onComplete(String name, List<String> phones) {
							ArrayList<ContactActionItem> actions = new ArrayList<QuestionFragment.ContactActionItem>();
							for (int i = 0; i < phones.size(); i++) {
								ContactActionItem item = new ContactActionItem();
								item.name = name;
								item.phone = phones.get(i);
								item.setText(item.phone);
								actions.add(item);
							}
							OActionSheet<ContactActionItem> actionSheet = new OActionSheet<ContactActionItem>(
									getContext());
							actionSheet.setCancel("取消");
							actionSheet.setDataProvider(actions);
							actionSheet
									.setOnActionItemClickListener(new OnActionItemClickListener<ContactActionItem>() {

										@Override
										public void onItemClick(
												OActionSheet<ContactActionItem> sheet,
												View v, int position,
												ContactActionItem dataItem) {
											final String smsPhoneNum = dataItem.phone;
											OAlert alert = new OAlert(
													getContext());
											alert.setTitle(dataItem.name + ":"
													+ smsPhoneNum);
											alert.setCancel("取消");
											alert.setOK("发送");
											alert.setListener(new OAlertListener() {

												@Override
												public boolean onOK(OAlert alert) {
													String body = "皮肤科医生移动客户端，您的掌上皮肤专家。权威专家，在线解答。告别排队奔波，三甲医院带回家。点击链接立即下载：http://t.cn/RzdrWrM";

													Uri uri = Uri
															.parse("smsto:"
																	+ smsPhoneNum);
													Intent intent = new Intent(
															Intent.ACTION_SENDTO,
															uri);
													intent.putExtra("sms_body",
															body);
													mSmsCatching = true;
													startActivity(intent);
													return false;
												}

												@Override
												public boolean onCancel(
														OAlert alert) {
													return false;
												}
											});
											alert.show();
										}
									});
							actionSheet.show(false, true);
						}
					});
				}

			}
		});
		dialog.show();
	}

	protected void doShareCallBack() {
		SysShareCallBackRequest req = new SysShareCallBackRequest();
		req.token = GlobalSettings.sToken;
		SysShareCallBackTask task = new SysShareCallBackTask();
		task.setRequest(req);
		add(task);
	}

	protected void onClickAddQuestion() {
		if (!CommonUtility.isNull(GlobalSettings.sUser)) {
			if (mCheckingQuestionLimit) {
				toast("请稍候...");
				return;
			}
			mCheckingQuestionLimit = true;
			QuestionLimitCheckRequest req = new QuestionLimitCheckRequest();
			req.token = GlobalSettings.sToken;
			QuestionLimitCheckTask task = new QuestionLimitCheckTask();
			task.setRequest(req);
			task.addListener(new NetTaskListener<QuestionLimitCheckTask.QuestionLimitCheckRequest, QuestionLimitCheckTask.QuestionLimitCheckResponse>() {

				@Override
				public void onException(
						INetTask<QuestionLimitCheckRequest, QuestionLimitCheckResponse> task,
						Exception e) {
					mCheckingQuestionLimit = false;
				}

				@Override
				public void onComplete(
						INetTask<QuestionLimitCheckRequest, QuestionLimitCheckResponse> task,
						QuestionLimitCheckResponse response) {
					mCheckingQuestionLimit = false;
					if (response.ResultCode != 200) {
						return;
					}
					if (response.Res.IsLimited == GlobalSettings.IS_TRUE) {
						showQuestionLimitDialog();
					} else {
						startActivity(new Intent(getContext(),
								CreateQuestionActivity.class));
					}
				}
			});
			add(task);
		} else {
			startActivity(new Intent(getContext(), LoginActivity.class));
		}
	}

	@Override
	protected void onRestart() {
		super.onRestart();

		Log.i("testmiandata", "onRestart:");

	}

	@Override
	protected void onStart() {
		super.onStart();

		Log.i("testmiandata", "onStart:");

		Bundle bundle = getIntent().getExtras();

		Log.i("testmiandata", "bundle.isnull:" + (bundle == null));

		if (bundle != null) {

			String data = bundle.getString("data");

			try {
				Log.i("testmaindata", "data:" + (new JSONObject(data)));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		if (GlobalSettings.sUser != null) {
			if (mLastInterceptTabIndex != -1) {
				if (GlobalSettings.mIsLoginActivity) {
					mLastInterceptTabIndex = 0;
				}
				mTab.setSelectedIndex(mLastInterceptTabIndex);
			}
		}
	}

	// 检查固化数据版本
	protected void doCheckDataVersion() {
		SysGetVerRequest req = new SysGetVerRequest();
		SysGetVerTask task = new SysGetVerTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<SysGetVerTask.SysGetVerRequest, SysGetVerTask.SysGetVerResponse>() {

			@Override
			public void onException(
					INetTask<SysGetVerRequest, SysGetVerResponse> task,
					Exception e) {
			}

			@Override
			public void onComplete(
					INetTask<SysGetVerRequest, SysGetVerResponse> task,
					final SysGetVerResponse response) {
				if (response.ResultCode != 200) {
					return;
				}
				if (response.Res == null) {
					return;
				}
				SysVerList cacheSysVerList = GlobalSettings
						.getSysVerList(getContext());
				new Thread() {
					public void run() {
						for (SysVerItem item : response.Res) {
							if (item.Name.equals("Hospital")) {
								if (item.Update) {
									// 更新医院信息
								}
							}
						}
						String str = CommonUtility.getStringToBean(
								new Hospital(), "Hospital.txt", getContext());
						// getHospitalItems();
						try {
							GlobalSettings.mHospital = JsonUtil.convert(str,
									Hospital.class);
							for (AreaHospital hos : GlobalSettings.mHospital) {
								for (SubAreaHospital subhos : hos.Value) {
									for (HospitalItem hositem : subhos.Value) {
										GlobalSettings.mHospitalItems
												.add(hositem);
									}
								}
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

				}.start();

				if (response.Res.equals(cacheSysVerList)) {
					return;
				}
				GlobalSettings.setSysVerList(getContext(), response.Res);
			}
		});
		add(task);

	}

	private void cacheHospital(final File file) {
		try {
			FileOutputStream out = new FileOutputStream(file);
			byte[] b = Util.getHtmlByteArray(GlobalSettings.SERVER_URL
					+ Constant.URL.REQUEST_HOSPITAL_JSON);
			out.write(b);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void getHospitalItems() {
		File file = new File(getCacheDir() + File.separator + "Hospital");
		FileReader fr;

		try {
			fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			StringBuilder sb = new StringBuilder();
			String s;
			while ((s = br.readLine()) != null) {
				sb.append(s);
			}

			GlobalSettings.mHospital = JsonUtil.convert(sb.toString(),
					Hospital.class);

			for (AreaHospital hos : GlobalSettings.mHospital) {
				for (SubAreaHospital subhos : hos.Value) {
					for (HospitalItem hositem : subhos.Value) {
						GlobalSettings.mHospitalItems.add(hositem);
					}
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onInterceptBackPressed() {
		if (super.onInterceptBackPressed()) {
			return true;
		}
		this.moveTaskToBack(true);
		return true;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (null != ShareQQUtils.getInstance(this).getTencent()) {
			ShareQQUtils.getInstance(this).getTencent()
					.onActivityResult(requestCode, resultCode, data);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// if (xxReceiver != null) {
		// this.unregisterReceiver(xxReceiver);
		// }

	}

	BroadcastReceiver xxReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(NavigateActivity.this, "收到信息", 0).show();
		}
	};

	/*
	 * @Override protected void onResume() { super.onResume();
	 * MobclickAgent.onResume(this); }
	 * 
	 * @Override protected void onPause() { super.onPause();
	 * 
	 * MobclickAgent.onPause(this); }
	 */

}